<template>
    <view class="savepadding">
        <view class="step-wrap">
            <view class="line"></view>
            <view class="step-item active">上传客户证件</view>
            <view class="step-item">扣款订单信息</view>
        </view>

        <view class="wrap"
              style="display:flex">
            <view>选择客户</view>
            <u--text type="primary"
                     align="right"
                     text="已选择客户"
                     v-if="isselectkehu"></u--text>
            <u--text type="primary"
                     align="right"
                     text="选择"
                     @click="xuanzekehu"></u--text>
        </view>

        <view class="wrap"
              style="display:flex"
              v-if="!isselectkehu">
            <view>客户类型</view>
            <template v-for="item in customtype">
                <u--text :text="item.dictLabel"
                         :type="item.dictLabel==activeCustomtype.dictLabel?'primary':''"
                         :key="item.dictLabel"
                         align="center"
                         @click="onselectcustomtype(item)"></u--text>
            </template>
        </view>

        <view class="card wrap"
              v-if="bankCount==0">
            <view class="header">
                <view class="title">上传证件照*</view>
            </view>
            <view class="desc">上传后自动填入相关信息</view>
            <!-- 身份证 -->
            <view class="img-wrap">
                <image :src="idCardImg|mmvImageUrl"
                       @click="onCheckIdCard('front')"></image>
                <image :src="idCardImgBack|mmvImageUrl"
                       @click="onCheckIdCard('back')"></image>
            </view>
            <!-- 银行卡 -->
            <view class="img-wrap">
                <image :src="bankImg|mmvImageUrl"
                       @click="onCheckBankCard('front')"></image>
                <image :src="bankImgBack|mmvImageUrl"
                       @click="onCheckBankCard('back')"></image>
            </view>
            <!-- 营业执照 -->
            <view class="img-wrap"
                  v-if="isqiye">
                <image :src="licenseImg|mmvImageUrl"
                       @click="onCheckLicenseImg('front')"></image>
            </view>
            <view class="desc">请核对您的身份证信息，若信息有误请重新扫描</view>
        </view>
        <view class="wrap">
            <view class="header">
                <view class="title">客户信息*</view>
            </view>
            <template v-if="isqiye">
                <view class="list">
                    <view class="label">企业名称*</view>
                    <view class="value">
                        <u--input border="none"
                                  inputAlign="right"
                                  v-model="customForm.customerName"
                                  placeholder="请输入" />
                    </view>
                </view>
                <view class="list">
                    <view class="label">联系人*</view>
                    <view class="value">{{customForm.contactPerson||'请上传身份证'}}</view>
                </view>
            </template>
            <template v-if="isgeren">
                <view class="list">
                    <view class="label">客户姓名</view>
                    <view class="value">{{customForm.customerName||'请上传身份证'}}</view>
                </view>
            </template>
            <view class="list">
                <view class="label">身份证号码</view>
                <view class="value">{{customForm.idCardNo||'请上传身份证'}}</view>
            </view>
            <view class="list">
                <view class="label">身份证有效期</view>
                <view class="value">{{customForm.idCardExpirydate||'请上传身份证'}}</view>
            </view>
            <view class="list">
                <view class="label">客户手机号码</view>
                <view class="value">
                    <u--input border="none"
                              inputAlign="right"
                              v-model="customForm.contactMobile"
                              placeholder="请输入手机号" />
                </view>
            </view>
            <template v-if="bankCount>0">
                <view class="list">
                    <view class="label">已绑定银行卡数量</view>
                    <view class="value">{{bankCount}}/张</view>
                </view>
            </template>
            <template v-else>
                <view class="list">
                    <view class="label">开户行</view>
                    <view class="value"
                          style="display:flex"
                          @click="showbankdeposit=true">
                        <text>{{bankForm.bankDeposit||'选择开户行'}}</text>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                </view>
                <!-- <view class="list tip">{{bankselected.quotaExplain}}</view> -->
                <view class="tip"
                      style="height:auto">{{bankselected.quotaExplain}}</view>
                <view class="list">
                    <view class="label">银行卡号</view>
                    <view class="value">
                        <u--input border="none"
                                  inputAlign="right"
                                  v-model="bankForm.bankCardNo"
                                  placeholder="请输入银行卡号" />
                    </view>
                </view>
                <view class="list">
                    <view class="label">银行预留手机号</view>
                    <view class="value">
                        <u--input border="none"
                                  inputAlign="right"
                                  v-model="bankForm.mobileNo"
                                  placeholder="请输入手机号" />
                    </view>
                </view>
            </template>
        </view>
        <view class="wrap"
              v-if="bankCount>0">
            <view class="header">
                <view class="title">说明：</view>
            </view>
            <view class="list">
                <view class="label">如需添加新卡可以在客户详情继续添加</view>
                <view class="value">
                    <u--text type="primary"
                             align="right"
                             text="去添加"
                             @click="qutianjia"></u--text>
                </view>
            </view>
        </view>
        <br>
        <!-- 按钮区 -->
        <view class="btn-btm-group-wrap">
            <view class="btn-btm-group savepadding">
                <view class="btn-btm"
                      @click="pre"
                      v-if="!isselectkehu">上一步</view>
                <view class="btn-btm active"
                      @click="next">下一步</view>
            </view>
        </view>
        <!-- 开户行选择 -->
        <u-picker :show="showbankdeposit"
                  :columns="[banklist]"
                  keyName="bankName"
                  @confirm="onconfirmbankdeposit"
                  @cancel="showbankdeposit=false"></u-picker>
    </view>
</template>

<script>
import * as systemApi from '@/api/system-api'
import * as customApi from '@/api/custom-api'
import qianyue from '@/pagesA/mixins/qianyue'

export default {
    mixins: [qianyue],
    data() {
        return {
            customtype: [], // 客户类型
            activeCustomtype: {}, // 当前选中客户类型
            showbankdeposit: false, // 显示银行列表
            banklist: [], // 支持银行列表
            bankselected: {}, // 当前选择开户行
            isselectkehu: false, // 是否已选择客户
            bankCount: 0, // 绑定银行卡数量
        };
    },
    computed: {
        isqiye() {
            return this.activeCustomtype.dictLabel == '企业';
        },
        isgeren() {
            return this.activeCustomtype.dictLabel == '个人';
        },
        // 身份证正面
        idCardImg() {
            return this.customForm.idCardImg || '/static/idCardImg.jpg';
        },
        // 身份证反面
        idCardImgBack() {
            return this.customForm.idCardImgBack || '/static/idCardImgBack.jpg';
        },
        // 营业执照
        licenseImg() {
            return this.customForm.licenseImg || '/static/yingye.png';
        },
        // 银行卡正面
        bankImg() {
            return this.bankForm.cardImgFront || '/static/bankImg.png';
        },
        // 银行卡背面
        bankImgBack() {
            return this.bankForm.cardImgBack || '/static/bankImgBack.png';
        },
    },
    onLoad(op) {
        if (op.kehu) {
            // console.log('解析客户信息',JSON.parse(op.kehu))
            const kehu = JSON.parse(op.kehu);
            this.isselectkehu = true; // 是选择的客户
            // this.bankCount = 2; // 绑定银行卡数量 测试
            this.bankCount = kehu.bankCount; // 绑定银行卡数量
            this.customForm.customerFlag = this.bankCount ? 3 : 2;  // 客户种类：1新客户 2未签约成功客户 3签约客户
            this.customForm.customerType = kehu.customerType;  // 客户类型；1企业2个人
            // this.customForm.customerId = kehu.customerId;  // 客户id
            this.setCustomerId(kehu.customerId);  // 客户id
            this.customForm.customerName = kehu.customerName;  // 客户名称
            this.customForm.idCardExpirydate = kehu.idCardExpirydate; // 身份证有效期
            this.customForm.contactPerson = kehu.contactPerson; // 联系人
            this.customForm.contactMobile = kehu.contactMobile; // 联系电话
            this.customForm.idCardImg = kehu.idCardImg; // 身份证正面
            this.customForm.idCardImgBack = kehu.idCardImgBack; // 身份证背面
            this.customForm.idCardExpirydate = kehu.idCardExpirydate; // 身份证失效日期
            this.customForm.idCardNo = kehu.idCardNo; // 身份证号
            this.customForm.licenseImg = kehu.licenseImg; // 营业执照图片
            this.bankForm.cardImgFront = kehu.cardImgFront; // 银行卡正面
            this.bankForm.cardImgBack = kehu.cardImgBack; // 银行卡背面
            this.bankForm.mobileNo = kehu.mobileNo; // 银行卡签约手机号
            this.bankForm.bankCardNo = kehu.bankCardNo; // 银行卡号
            this.bankForm.bankDeposit = kehu.bankDeposit; // 开户行
            this.bankForm.expireDate = kehu.expireDate; // 信用卡时效日期
            this.bankForm.cvv = kehu.cvv; // 信用卡安全吗
        } else {
            this.setCustomerId();
        }
        // this.customForm.customerFlag = 3;
    },
    async mounted() {
        try {
            this.getcustomtype(); // 获取客户类型
            this.getbanklist(); // 获取支持银行列表
        } catch (error) {
            console.error(error);
            const title = error?.message || '网络错误';
            uni.showToast({ title, icon: 'error' });
        }
    },
    methods: {
        pre() {
            uni.navigateBack();
        },
        next() {
            // 参数验证
            try {
                console.log(this.customForm.customerFlag)
                if (this.customForm.customerFlag != 3) {
                    this.verify();
                }
                uni.navigateTo({
                    url: `/pagesA/qianyue/order?data=${JSON.stringify(this.$data)}`
                });
            } catch (error) {
                uni.showToast({ title: error, icon: 'error' });
                return;
            }
        },
        verify() {
            // 参数验证
            if (!this.customForm.idCardImg) {
                throw '缺少身份证正面';
            }
            if (!this.customForm.idCardImgBack) {
                throw '缺少身份证反面';
            }
            if (!this.bankForm.cardImgFront) {
                throw '缺少银行卡正面';
            }
            // this.bankForm.cardImgBack
            if (!this.bankForm.cardImgBack || this.bankImgBack == '/static/bankImgBack.png') {
                throw '缺少银行卡反面';
            }
            if (this.activeCustomtype.dictLabel == '企业') {
                if (!this.customForm.licenseImg) {
                    throw '缺少营业执照';
                }
            }
            if (!this.customForm.customerName) {
                throw '缺少客户姓名';
            }
            if (!this.customForm.idCardNo) {
                throw '缺少身份证号码';
            }
            if (!this.customForm.idCardExpirydate) {
                throw '缺少有效期';
            }
            if (!uni.$u.test.mobile(this.customForm.contactMobile)) {
                throw '手机号格式错误';
            }
            if (!this.bankForm.bankDeposit) {
                throw '缺少开户行';
            }
            if (!this.bankForm.bankCardNo) {
                throw '缺少银行卡号';
            }
            if (!uni.$u.test.mobile(this.bankForm.mobileNo)) {
                throw '手机号格式错误';
            }
        },
        /**
         * 选择客户
         */
        xuanzekehu() {
            uni.navigateTo({
                url: `/pagesA/qianyue/kehu`
            });
        },
        /**
         * 跳转添加银行卡
         */
        qutianjia() {
            uni.navigateTo({
                url: `/pagesB/my-custom/custom-detail?customerId=${this.customForm.customerId}`
                // url: `/pagesB/my-custom/addbank?customId=${this.customForm.customerId}`
            });
        },
        /**
         * 获取客户类型
         */
        async getcustomtype() {
            try {
                const result = await systemApi.dict('custom_type');
                this.customtype = result.data || [];
                const defaulItem = this.customtype.find(val => val.dictValue == this.customForm.customerType);
                console.log(defaulItem)
                if (defaulItem) {
                    this.activeCustomtype = defaulItem
                } else {
                    this.activeCustomtype = this.customtype[0]; // 设置默认选中客户类型
                }
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 获取支持银行列表
         */
        async getbanklist() {
            try {
                const result = await customApi.bankList();
                this.banklist = result.rows || [];
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 选择客户类型
         */
        onselectcustomtype(item) {
            this.activeCustomtype = item;
            this.customForm.customerType = item.dictValue;
        },
        /**
         * 选择图片
         */
        chooseImage() {
            return new Promise((resolve, reject) => {
                uni.chooseImage({
                    // sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
                    success({ tempFilePaths }) {
                        resolve(tempFilePaths);
                    },
                    fail(err) {
                        uni.showToast({ title: '图片选择失败', icon: 'error' });
                        reject(err);
                    }
                })
            });
        },
        /**
         * 上传图片
         */
        async upload(url) {
            uni.showToast({ title: '图片上传中...', icon: 'loading' });
            console.log(url)
            const result = await customApi.uploadfiles({
                name: 'file',
                filePath: url,
            });
            uni.showToast({ title: '图片上传成功', icon: 'success' });
            return result;
        },
        /**
         * 提交身份证
         */
        async onCheckIdCard(idCardSide) {
            try {
                const tempFilePaths = await this.chooseImage();
                const { fileName } = await this.upload(tempFilePaths[0]);
                const result = await customApi.idCard({
                    url: fileName.replace('/image-server', ''),
                    idCardSide,
                });
                if (idCardSide == 'front') {
                    this.customForm.idCardImg = fileName; // 身份证正面
                    if (this.isgeren) {
                        this.customForm.customerName = result.data.name; // 客户名称
                    }
                    if (this.isqiye) {
                        this.customForm.contactPerson = result.data.name; // 联系人
                    }
                    this.customForm.idCardNo = result.data.idCard; // 身份证号
                }
                if (idCardSide == 'back') {
                    this.customForm.idCardImgBack = fileName; // 身份证反面
                    this.customForm.idCardExpirydate = result.data.endDate; // 身份证有效期
                }
            } catch (error) {
                uni.showToast({ title: error, icon: 'error' });
            }
        },
        /**
         * 提交营业执照
         */
        async onCheckLicenseImg() {
            try {
                const tempFilePaths = await this.chooseImage();
                const { fileName } = await this.upload(tempFilePaths[0]);
                this.customForm.licenseImg = fileName; // 营业执照
            } catch (error) {
                uni.showToast({ title: error, icon: 'error' });
            }
        },
        /**
         * 提交银行卡
         */
        async onCheckBankCard(side) {
            try {
                const tempFilePaths = await this.chooseImage();
                const { fileName } = await this.upload(tempFilePaths[0]);
                if (side == 'front') {
                    this.bankForm.cardImgFront = fileName; // 银行卡正面
                }
                if (side == 'back') {
                    this.bankForm.cardImgBack = fileName; // 银行卡背面
                }
            } catch (error) {
                uni.showToast({ title: error, icon: 'error' });
            }
        },
        /**
         * 选择开户行(确认选择)
         */
        onconfirmbankdeposit({ value }) {
            this.bankselected = value[0] || {}; // 当前选择开户行id
            this.bankForm.bankDeposit = this.bankselected.bankName; // 开户行
            this.showbankdeposit = false; // 显示银行列表
        },
    },
}
</script>

<style lang="scss" scoped>
@import '@/styles/mmv.scss';

.card {
    .img-wrap {
        margin-bottom: 34upx;
        display: flex;
        justify-content: space-between;
        image {
            width: 330upx;
            height: 184upx;
        }
    }
    .desc {
        margin-bottom: 49upx;
        font-size: 26upx;
        font-weight: bold;
        color: #999;
    }
}
</style>
